package cn.iocoder.yudao.module.wecom.service.taggroup;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.wecom.dal.dataobject.apiconfig.WeComApiConfigDO;
import cn.iocoder.yudao.module.wecom.dal.dataobject.tags.WeTagsDO;
import cn.iocoder.yudao.module.wecom.dal.mysql.apiconfig.WeComApiConfigMapper;
import cn.iocoder.yudao.module.wecom.dal.mysql.tags.WeTagsMapper;
import cn.iocoder.yudao.module.wecom.http.WeApi;
import cn.iocoder.yudao.module.wecom.service.apiconfig.WeComApiConfigService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.wecom.controller.admin.taggroup.vo.*;
import cn.iocoder.yudao.module.wecom.dal.dataobject.taggroup.WeTagGroupDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wecom.dal.mysql.taggroup.WeTagGroupMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wecom.enums.ErrorCodeConstants.*;

/**
 * 标签分组 Service 实现类
 *
 * @author 数创万维
 */
@Service
@Validated
public class WeTagGroupServiceImpl implements WeTagGroupService {

    @Resource
    private WeTagGroupMapper weTagGroupMapper;

    @Resource
    private WeTagsMapper weTagsMapper;
    @Resource
    private WeComApiConfigMapper weComApiConfigMapper;

    @Override
    public void createWeTagGroup(WeTagGroupSaveReqVO createReqVO) {
        // 插入
        WeComApiConfigDO apiConfig = weComApiConfigMapper.getWeComApiConfig();
        final String accessToken = apiConfig.getAccessToken();
        Map<String, Object> postData = new HashMap<>();
        postData.put("group_name", createReqVO.getGroupName());
        postData.put("order", createReqVO.getSort());
        List<String> tagList = StrUtil.split(createReqVO.getTagName(), ",");
        postData.put("tag", tagList.stream().map(cus -> MapUtil.of("name", cus)).collect(Collectors.toList()));
        WeApi weApi = new WeApi(accessToken).body(postData);
        JSONObject jsonObject = weApi.addCorpTag();

        if (Objects.equals(0, jsonObject.getInt("errcode"))) {
            JSONObject data = jsonObject.getJSONObject("tag_group");
            String groupId = data.getStr("group_id");
            WeTagGroupDO weTagGroup = BeanUtils.toBean(createReqVO, WeTagGroupDO.class);
            weTagGroup.setGroupId(groupId);
            weTagGroupMapper.insert(weTagGroup);

            saveTagItem(data, groupId);
        }
    }

    private void saveTagItem(JSONObject data, String groupId) {
        JSONArray tagsArray = data.getJSONArray("tag");
        tagsArray.forEach(item2 -> {
            JSONObject data2 = JSONUtil.parseObj(item2);
            WeTagsDO tagsDO = new WeTagsDO();
            tagsDO.setGroupId(groupId);
            tagsDO.setTagId(data2.getStr("id"));
            tagsDO.setName(data2.getStr("name"));
            tagsDO.setSort(data2.getInt("order"));
            weTagsMapper.insert(tagsDO);
        });
    }

    @Override
    public void updateWeTagGroup(WeTagGroupSaveReqVO updateReqVO) {
        // 更新
        WeComApiConfigDO apiConfig = weComApiConfigMapper.getWeComApiConfig();
        final String accessToken = apiConfig.getAccessToken();
        Map<String, Object> postData = new HashMap<>();
        postData.put("id", updateReqVO.getGroupId());
        postData.put("name", updateReqVO.getGroupName());
        postData.put("order", updateReqVO.getSort());
        WeApi weApi = new WeApi(accessToken).body(postData);
        JSONObject jsonObject = weApi.editCorpTag();
        if (Objects.equals(0, jsonObject.getInt("errcode"))) {
            WeTagGroupDO updateObj = BeanUtils.toBean(updateReqVO, WeTagGroupDO.class);
            weTagGroupMapper.updateById(updateObj);
        }
    }

    @Override
    public void deleteWeTagGroup(Long id) {
        // 删除
        WeComApiConfigDO apiConfig = weComApiConfigMapper.getWeComApiConfig();
        final String accessToken = apiConfig.getAccessToken();
        Map<String, Object> postData = new HashMap<>();
        WeTagGroupDO data = getWeTagGroup(id);
        postData.put("group_id", ListUtil.of(data.getGroupId()));
        WeApi weApi = new WeApi(accessToken).body(postData);
        JSONObject jsonObject = weApi.delCorpTag();
        if (Objects.equals(0, jsonObject.getInt("errcode"))) {
            weTagGroupMapper.deleteById(id);
        }
    }

    @Override
    public WeTagGroupDO getWeTagGroup(Long id) {
        return weTagGroupMapper.selectById(id);
    }

    @Override
    public List<WeTagGroupDO> getWeTagGroupList() {
        return weTagGroupMapper.selectList();
    }

    @Override
    public PageResult<WeTagGroupDO> getWeTagGroupPage(WeTagGroupPageReqVO pageReqVO) {
        return weTagGroupMapper.selectPage(pageReqVO);
    }

    @Override
    public List<WeTagGroupDO> getWeTagGroupListByBatchId(List<String> groupIds) {
        return weTagGroupMapper.selectList(new LambdaQueryWrapperX<WeTagGroupDO>().in(WeTagGroupDO::getGroupId, groupIds));
    }

    @Override
    public Map<String, WeTagGroupDO> getWeTagGroupMapByBatchId(List<String> groupIds) {
        List<WeTagGroupDO> list = getWeTagGroupListByBatchId(groupIds);
        if (CollectionUtil.isNotEmpty(list)) {
            return CollectionUtils.convertMap(list, WeTagGroupDO::getGroupId);
        }
        return Collections.emptyMap();
    }

    @Override
    public Map<String, WeTagGroupDO> getWeTagGroupMap() {
        List<WeTagGroupDO> list = weTagGroupMapper.selectList();
        return getWeTagGroupMapByBatchId(list.stream().map(WeTagGroupDO::getGroupId).collect(Collectors.toList()));
    }

    @Override
    public void syncTags() {
        WeComApiConfigDO apiConfig = weComApiConfigMapper.getWeComApiConfig();
        WeApi weApi = new WeApi(apiConfig.getAccessToken());
        JSONObject jsonObject = weApi.getCorpTag();
        JSONArray array = jsonObject.getJSONArray("tag_group");
        if (!array.isEmpty()) {
            // 清空重建
            weTagGroupMapper.delete(new LambdaQueryWrapperX<>());
            weTagsMapper.delete(new LambdaQueryWrapperX<>());
        }
        array.forEach(item -> {
            JSONObject data = JSONUtil.parseObj(item);
            WeTagGroupDO tagGroupDO = new WeTagGroupDO();
            tagGroupDO.setGroupId(data.getStr("group_id"));
            tagGroupDO.setGroupName(data.getStr("group_name"));
            tagGroupDO.setSort(data.getInt("order"));
            weTagGroupMapper.insert(tagGroupDO);
            final String groupId = tagGroupDO.getGroupId();
            saveTagItem(data, groupId);
        });
    }
}